package com.asset.dispoal.nature.service.commom;

import com.asset.dispoal.nature.domain.db.entity.GbNature;
import com.asset.dispoal.nature.domain.db.mapper.GbNatureMapper;
import com.asset.dispoal.nature.dto.requset.GbNatureRequest;
import com.asset.dispoal.nature.dto.response.GbNatureResponse;
import com.asset.dispoal.nature.service.converter.GbNatureConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qr
 * @date 2022/3/7$
 */
@Component
public class QueryAllNatureCommand implements BaseCommand<GbNatureRequest, List<GbNatureResponse>> {

    @Autowired
    GbNatureMapper gbNatureMapper;

    @Override
    public List<GbNatureResponse> execute(GbNatureRequest request) {
        final GbNature gbNature = GbNatureConverter.INSTANCE.reqToDo(request);
        gbNature.setPermission((String) GlobalHeaderThreadLocal.getOrException().getExtraMap().get("permission"));

        final List<GbNature> gbNatures = gbNatureMapper.queryList(gbNature);
        if (CollectionUtil.isEmpty(gbNatures) || gbNatures.size() == 1) {
            return GbNatureConverter.INSTANCE.dosToRes(gbNatures);
        }
        final List<GbNatureResponse> gbNatureResponses = GbNatureConverter.INSTANCE.dosToRes(gbNatures);
        List<GbNatureResponse> collect = gbNatureResponses.stream().filter(item -> StringUtil.isBlank(item.getParentId())).collect(Collectors.toList());
        gbNatureResponses.removeAll(collect);
        return this.recursion(gbNatureResponses, collect);
    }


    private List<GbNatureResponse> recursion(List<GbNatureResponse> sysAddressResponses, List<GbNatureResponse> collect) {
        for (GbNatureResponse response : collect) {
            final List<GbNatureResponse> sysAddressResponseList = sysAddressResponses.stream().filter(itme -> itme.getParentId().equals(response.getId())).collect(Collectors.toList());
            response.setResponseList(sysAddressResponseList);
            recursion(sysAddressResponses, sysAddressResponseList);
        }
        return collect;
    }
}
